import { Suspense } from 'react';
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { routes } from './routes';
import { AuthGuard, PublicGuard } from './guards';
import MainLayout from '@/components/layout/MainLayout';
import { LoadingFallback } from '@/components/common/Loading';

// Error Boundary for route-level errors
import { ErrorBoundary } from 'react-error-boundary';
import { ErrorFallback } from '@/components/common/ErrorFallback';

const AppRouter: React.FC = () => {
  return (
    <BrowserRouter>
      <ErrorBoundary FallbackComponent={ErrorFallback}>
        <Routes>
          {/* Auth Routes - Public */}
          {routes
            .filter(route => route.isPublic)
            .map(route => (
              <Route
                key={route.path}
                path={route.path}
                element={
                  <PublicGuard>
                    <Suspense fallback={<LoadingFallback />}>
                      <route.element />
                    </Suspense>
                  </PublicGuard>
                }
              />
            ))}

          {/* Protected Routes - Require Authentication */}
          {routes
            .filter(route => !route.isPublic)
            .map(route => (
              <Route
                key={route.path}
                path={route.path}
                element={
                  <AuthGuard>
                    <MainLayout>
                      <Suspense fallback={<LoadingFallback />}>
                        <route.element />
                      </Suspense>
                    </MainLayout>
                  </AuthGuard>
                }
              />
            ))}

          {/* Catch-all route - 404 */}
          <Route
            path='*'
            element={
              <div className='flex justify-center items-center min-h-screen'>
                <div className='text-center'>
                  <h1 className='mb-4 text-4xl font-bold text-gray-900'>404</h1>
                  <p className='mb-6 text-gray-600'>页面未找到</p>
                  <Navigate to='/dashboard' replace />
                </div>
              </div>
            }
          />
        </Routes>
      </ErrorBoundary>
    </BrowserRouter>
  );
};

export default AppRouter;
